(ns scripts.cljmon.agent.client
  (:use json-rpc.http.client
        scripts.cljmon.config)
  (:require clojure.string))

(defn agent-to-url [agent]
  (when agent
    (cond
      (string? agent) (if-let [[_ host port] (re-matches #"(?i)^(?:http://)?([^/:]+)(?::(\d+))?(?:/.*)?$" agent)]
                        (str host ":" (or port DEFAULT_AGENT_PORT))
                        (throw (Exception. (str "Invalid agent: " agent))))
      (map? agent) (let [{:keys [url host port]} agent]
                     (cond
                       url (agent-to-url url)
                       host (agent-to-url (str host ":" (or port DEFAULT_AGENT_PORT)))
                       :else (throw (Exception. (str "Invalid agent: " agent)))))
      :else (throw (Exception. (str "Invalid agent: " agent))))))

(defn agent-to-map [agent]
  (let [url (agent-to-url agent)
        [_ host port] (re-matches #"(.+):(\d+)" url)]
    (when-not host
      (throw (Exception. (str "Agent parsing error: " agent))))
    {:url url :host host :port (Integer/parseInt port)}))

(defn- to-real-url [url]
  (if-let [[_ host] (re-matches #"(?:http://)?([^:/]+:\d+)(?:/(?:api/json-rpc/?)?)?" url)]
    (format "http://%s/api/json-rpc" host)
    (throw (Exception. (str "Invalid URL: " url)))))

(defn register-query [host id q]
  (read-string (json-rpc-call (to-real-url host) "register" [id (pr-str q)])))

(defn execute-query [host id]
  (read-string (json-rpc-call (to-real-url host) "query" [id])))

(defn unregister-query [host id]
  (json-rpc-call (to-real-url host) "unregister" [id]))

;(prn (register-query "localhost:17701" "1" {:queries [:timestamp {:type :process-info :by :name :name "firefox" :log-process-arguments true}]}))
;(prn (json-rpc-call (to-url "localhost:17701") "debug" []))
;(prn (execute-query "localhost:17701" "1"))
;(prn (json-rpc-call (to-url "localhost:17701") "debug" []))
;(prn (unregister-query "localhost:17701" "1"))
;(prn (json-rpc-call (to-url "localhost:17701") "debug" []))

